package com.djx.comm.util;


import com.djx.comm.Constant;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 工具类
 * @author WangHui
 * @since 2017/1/9
 */
public class StringUtils {
    //处理Excel上传用Math.abs(value - (long)value)<EXP 来判断是整数还是浮点数
    public static double EXP = 0.0000000000000001;
    private final static Pattern MOBILE = Pattern.compile("^1(3[0-9]|4[0-9]|5[0-9]|8[0-9])\\d{8}$");
    private final static Pattern EMAILER = Pattern.compile("[\\w[.-]]+@[\\w[.-]]+\\.[\\w]+");
    //默认小数位
    private final static int DEFAULT_SCALE = 2;


    /**
     * 异常信息拼装
     * @param e
     * @return
     */
    public static String callStatck( Exception e) {
        StringBuffer sb = new StringBuffer();
        Throwable cause = e.getCause();
        String errormsg  = e.toString();
        StackTraceElement[] stackElements = e.getStackTrace();
        if(cause != null) {
            stackElements = cause.getStackTrace();
            errormsg = cause.toString();
        }
        sb.append("异常错误：" + errormsg + "。\n 详细异常：");
        if (stackElements != null) {
            for (int i = 0; i < stackElements.length; i++) {
                String className = stackElements[i].getClassName();
                if(className.contains("com.mango")) {
                    sb.append("类名：" + stackElements[i].getClassName() + "   ");
                    sb.append("文件名：" + stackElements[i].getFileName() + "   ");
                    sb.append("行数：" + stackElements[i].getLineNumber() + "   ");
                    sb.append("方法名：" + stackElements[i].getMethodName() + " \n ");
                }
            }
        }
        return sb.toString();
    }

    /**
     * 计算字符串长度  中文算两个字符
     * @param str
     * @return
     */
    public static int getStrLen (String str) {
        int len = 0;
        if (str != null) {
            for (int i=0; i<str.length(); i++) {
                len++;
                if (str.charAt(i) > 254) {
                    len++;
                }
            }
        }
        return len;
    }
    /**
     * 将指定字符串首字母转换成大写字母
     *
     * @param str
     *            指定字符串
     * @return 返回首字母大写的字符串
     */
    public static String firstCharUpperCase(String str) {
        StringBuffer buffer = new StringBuffer(str);
        if (buffer.length() > 0) {
            char c = buffer.charAt(0);
            buffer.setCharAt(0, Character.toUpperCase(c));
        }
        return buffer.toString();
    }
    /**
     * 截取字符串
     * @param str
     * @param len
     * @return
     */
    public static String getSubStr(String str, int len) {
        if (getStrLen(str) > len) {
            StringBuffer sb = new StringBuffer();
            int index = 0;
            for (int i=0; i<str.length(); i++) {
                index++;
                if (str.charAt(i) > 254) {
                    index++;
                }
                if (index <= len) {
                    sb.append(str.charAt(i));
                }
            }
            str = sb.toString() + "…";
        }
        return str;
    }


    /**
     * 设置导出文件名编码问题
     * @param request
     * @param response
     * @param fileName
     */
    public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        final String userAgent = request.getHeader("USER-AGENT");
        try {
            String finalFileName = null;
            if(request.getHeader("User-Agent").toLowerCase() .indexOf("MSIE") > 0){//IE浏览器
                finalFileName = URLEncoder.encode(fileName,"UTF8");
            }else if(request.getHeader("User-Agent").toLowerCase() .indexOf("firefox") > 0 ){//google,火狐浏览器
                finalFileName = new String(fileName.getBytes(), "ISO8859-1");
            }else{
                finalFileName = URLEncoder.encode(fileName,"UTF8");//其他浏览器
            }
            response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//这里设置一下让浏览器弹出下载提示框，而不是直接在浏览器中打开
        } catch (UnsupportedEncodingException e) {
        }
    }
    /**
     * 判断指定字符串是否等于null或空字符串
     *
     * @param str
     *            指定字符串
     * @return 如果等于null或空字符串则返回true，否则返回false
     */
    public static boolean isBlank(String str) {
        return str == null || "".equals(str.trim());
    }

    /**
     * 判断指定字符串是否不等于null和空字符串
     *
     * @param str
     *            指定字符串
     * @return 如果不等于null和空字符串则返回true，否则返回false
     */
    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }

    //检查是否合法的手机号码
    public static boolean isMobile(String str){
        if(isNull(str)) {
            return false;
        }
        return MOBILE.matcher(str).find();
    }
    //检查是否合法的Email
    public static boolean isEmailer(String str){
        if(isNull(str)) {
            return false;
        }
        return EMAILER.matcher(str).find();
    }
    //检查字符串是否是数字
    public static boolean isNumeric(String str){
        if(isNull(str)) {
            return false;
        }
        for(int i= str.length(); --i >=0;){
            int chr = str.charAt(i);
            if(chr < 48 || chr > 57) {
                return false;
            }
        }
        return true;
    }
    public static boolean isFloatAction(String str,int minPri,int maxPri){
        if(isNull(str)) {
            return false;
        }
        boolean isOk = Pattern.matches("^[-|+]?\\d+\\d*([.]\\d*)?$",str);
        if(!isOk) {
            return false;
        }
        int index = str.indexOf('.');
        if(index > -1){
            int floatLenth = str.substring(index+1).length();
            if(floatLenth >= minPri && floatLenth <=maxPri){
                return true;
            }else{
                return false;
            }
        }else{
            return true;
        }
    }


    /**
     * 过滤<, >,,\n 字符的方法。
     *  需要过滤的字符
     * 完成过滤以后的字符串&amp;nbsp;&amp;nbsp;&amp;nbsp;
     */
    public static String convertStr2Html(String input) {
        if (StringUtils.isNull(input)) {
            return input;
        }
        input = input.replaceAll("&", "&amp;");
        input = input.replaceAll("<", "&lt;");
        input = input.replaceAll(">", "&gt;");
        input = input.replaceAll(" ", "&nbsp;");
        input = input.replaceAll("'", "&#39;");
        input = input.replaceAll("\r\n", "<br/>");
        input = input.replaceAll("\n", "<br/>");
        input = input.replaceAll("\"", "&quot;");
        return input;
    }

    /**
     * @param input
     *            需要过滤的字符
     * @return 修改时完成反过滤以后的字符串
     */
    public static String convertHtml2Str(String input){
        if (StringUtils.isNull(input)) {
            return input;
        }
        input = input.replaceAll("&#39;", "'");
        input = input.replaceAll("&nbsp;", " ");
        input = input.replaceAll("&quot;", "\"");
        input = input.replaceAll("<br>", "\r\n");
        input = input.replaceAll("<br/>", "\r\n");
        input = input.replaceAll("&amp;", "&");
        input = input.replaceAll("&gt;", ">");
        input = input.replaceAll("&lt;", "<");
        return input;
    }

    public static boolean isNull(String str){
        return str == null || str.isEmpty() || "".equals(str.trim());
    }

    public static boolean isNull2(String str){
        return str == null || str.isEmpty() || "".equals(str.trim()) || "null".equals(str.trim());
    }

    // 判断字符或者字符对象是否为空
    public static boolean isNotNull(Object obj) {
        return !isNull(obj);
    }

    // 判断字符或者字符对象是否为空
    public static boolean isNull(Object obj) {
        if (obj == null) {
            return true;
        } else if (obj instanceof String) {
            if ("".equals(obj) || "".equals(obj.toString().trim())) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 下划线转驼峰法
     * @param line 源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰
     * @return 转换后的字符串
     */
    public static String underline2Camel(String line,boolean smallCamel){
        if(line==null||"".equals(line)){
            return "";
        }
        StringBuffer sb=new StringBuffer();
        String regex = "([A-Za-z\\d]+)(_)?";
        Pattern pattern=Pattern.compile(regex);
        Matcher matcher=pattern.matcher(line);
        while(matcher.find()){
            String word=matcher.group();
            sb.append(smallCamel&&matcher.start()==0?Character.toLowerCase(word.charAt(0)):Character.toUpperCase(word.charAt(0)));
            int index=word.lastIndexOf('_');
            if(index>0){
                sb.append(word.substring(1, index).toLowerCase());
            }else{
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }

    // 判断字符或者字符对象是否为空 包括"null"字符串
    public static boolean isNull2(Object obj) {
        if (obj == null) {
            return true;
        } else if (obj instanceof String) {
            if ("".equals(obj) || "".equals(obj.toString().trim())||"null".equals(obj.toString().trim())) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    // 判断对象数组是否为空
    public static boolean isNull(Object[] objArray) {
        if (objArray == null) {
            return true;
        } else if (objArray.length < 1) {
            return true;
        } else {
            return false;
        }
    }

    public static String getListToStr(List<?> list, boolean isValue, String keyValue){
        if(isNull(keyValue) || list == null || list.size() <=0) {
            return null;
        }
        int size = list.size();
        StringBuilder html = new StringBuilder();
        Hashtable<String,Object> hashMap = null;
        if(isValue){
            Object value = null;
            for (int i = 0; i < size; i++) {
                hashMap = (Hashtable<String, Object>) list.get(i);
                value = hashMap.get(keyValue);
                if(!isNull(value)){
                    html.append("'").append(value).append("'");
                    if (i < (size - 1)) {
                        html.append(",");
                    }
                }
            }
        }else{
            Object value = null;
            for (int i = 0; i < size; i++) {
                hashMap = (Hashtable<String, Object>) list.get(i);
                value = hashMap.get(keyValue);
                if(!isNull(value)){
                    html.append(value);
                    if (i < (size - 1)) {
                        html.append(",");
                    }
                }
            }
        }
        return html.toString();
    }
    // 把数组转化为 形式为'a','b','..'
    public static String convertToQueryArrayStr(String[] array,boolean isStringVal,String... spCode) {
        if (array == null || array.length < 1) {
            return null;
        }
        int size = array.length;
        StringBuilder html = new StringBuilder();
        if (spCode.length == 0 || spCode[0] == null) {
            if(isStringVal){
                for (int i = 0; i < size; i++) {
                    html.append("'").append(array[i]).append("'");
                    if (i < (size - 1)) {
                        html.append(",");
                    }
                }
            }else{
                for (int i = 0; i < size; i++) {
                    html.append(array[i]);
                    if (i < (size - 1)) {
                        html.append(",");
                    }
                }
            }
        }else{
            if(isStringVal){
                for (int i = 0; i < size; i++) {
                    html.append("'").append(array[i].split(spCode[0])[Integer.valueOf(spCode[1])]).append("'");
                    if (i < (size - 1)) {
                        html.append(",");
                    }
                }
            }else{
                for (int i = 0; i < size; i++) {
                    html.append(array[i].split(spCode[0])[Integer.valueOf(spCode[1])]);
                    if (i < (size - 1)) {
                        html.append(",");
                    }
                }
            }
        }
        return html.toString();
    }

    public static String urlEncode(String value){
        String urlEncode = null;
        try {
            urlEncode = URLEncoder.encode(value, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        return urlEncode;
    }

    public static String urlDecode(String value){
        String urlDecode = null;
        try {
            urlDecode = URLDecoder.decode(value, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        return urlDecode;
    }
    //小写金额转换成大写金额
    public static String amToChinese(String qstr){
        String result ="";
        String maxStr ="零壹贰叁肆伍陆柒捌玖";
        String minStr ="分角整元拾佰仟万拾佰仟亿拾佰仟";
        if(isNull(qstr)){
            return result ="金额为空,不能转换大写金额。";
        }
        String qtemp = qstr.trim();
        try{
            int len = 0;
            if(qtemp.indexOf(".") == -1){
                len = qtemp.length();
            }else{
                len = qtemp.indexOf(".");
            }
            if(len > minStr.length()-3){
                return result ="金额最大只能精确到仟亿,小数点只允许两位。";
            }
            int nl =0;
            String num = null;
            String unit = null;
            for(int i=0; i<qtemp.length(); i++){
                if(i > len +2){
                    break;
                }
                if(i == len){
                    continue;
                }
                nl=Integer.parseInt(String.valueOf(qtemp.charAt(i)));
                num = maxStr.substring(nl,nl+1);
                nl = len -i+2;
                unit = minStr.substring(nl,nl+1);
                result = result.concat(num).concat(unit);
            }
            if(len ==qtemp.length() || len == (qtemp.length()-1)){
                result = result.concat("整");
            }
            if(len == (qtemp.length() -2)){
                result = result.concat("零分");
            }
        }catch(Exception e){
            e.printStackTrace();
        }

        return result;
    }
    //提供精确的小数位四舍五入处理。
    public static String rounds(String qstr,Integer scale){
        if(scale < 0){
            throw new IllegalArgumentException("四舍五入小数点后保留几位请提供。");
        }
        if(isNull(qstr) || "0".equals(qstr)){
            return  "0";
        }
        BigDecimal mData = new BigDecimal(qstr);
        return mData.setScale(scale,BigDecimal.ROUND_HALF_UP).toString();
    }
    //提供精确的乘法运算，且保留小数位四舍五入处理。
    public static String muls(String v1,String v2,int scale){
        if(isNull(v1) || isNull(v2)){
            return  "0";
        }
        BigDecimal b1 = new BigDecimal(v1);
        BigDecimal b2 = new BigDecimal(v2);
        return rounds(b1.multiply(b2).toString(),scale);
    }
    // 判断两个字符串是否相等
    public static boolean equal(String str1, String str2) {
        return str1.equals(str2);
    }

    // 判断两个整数是否相等
    public static boolean equal(int str1, int str2) {
        if (str1 == str2) {
            return true;
        } else {
            return false;
        }
    }

    // 判断数字是否为零,如果为零,则返回新值
    public static int isZero(int val, int newVal) {
        if (val == 0) {
            return newVal;
        } else {
            return val;
        }
    }
    //获取hashtable 内指定属性值
    public static String getHashStr(Hashtable<?,?> hash,String porterty) {
        if (hash != null && hash.size() > 0) {
            return hash.get(porterty)== null ? null : hash.get(porterty).toString().trim();
        } else {
            return null;
        }
    }
    /**
     * 格式化数字
     * @param strNumber
     * @return
     */
    public static String getFormatNumber(String strNumber){
        if(isNull(strNumber)){
            return "0.00";
        }
        double number=0;
        try {
            number=Double.parseDouble(strNumber);

        } catch (Exception e) {
            return "0.00";
        }
        NumberFormat nf = NumberFormat.getInstance();
        //设置是否使用分组
        nf.setGroupingUsed(true);
        //设置最大整数位数
        nf.setMaximumIntegerDigits(10);
        //设置最小整数位数
        nf.setMinimumIntegerDigits(1);
        //设置最大小数位数
        nf.setMaximumFractionDigits(8);
        //设置最小小数位数
        nf.setMinimumFractionDigits(3);

        return nf.format(number);

    }
    /**
     * 格式化数字
     * @param str
     * @return
     */
    public static String getFormatNumberByNber(String str,int numbers){
        StringBuilder sb=new StringBuilder();
        if(str==null || "".equals(str.trim()) || "null".equals(str)){
            return "";
        }
        str=rounds(str,2);
        if(str.indexOf(".")==-1){
            return sb.append(str).append(".00").toString();
        }else{
            String st=str.substring(str.indexOf(".")+1);
            if(st.length()>=numbers){
                return sb.append(str.substring(0,str.indexOf("."))).append(".").append(st.substring(0,numbers)).toString();
            }else{
                sb.append(str);
                for(int i=0;i<(numbers-st.length());i++){
                    sb.append("0");
                }
                return sb.toString();
            }
        }
    }
    /**
     * 解码
     * @param str
     * @return
     */
    public static String decodeStr(String str){
        if(str==""||str==null){
            return null;
        }
        String decodeStr;
        try {
            decodeStr = URLDecoder.decode(str,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        return decodeStr;
    }

    /**
     * 截取带小数点的字符串
     * @param str
     * @return
     */
    public static String getSubString(String str){
        if(isNull(str)){
            return "";
        }
        if(str.indexOf(".")==-1){
            return str;
        }

        return str.substring(0, str.indexOf("."));

    }

    public static String getPercent(int x,int total){
        if(total>0){
            double xDouble=x*1.0;
            double tempresult=xDouble/total;
            //NumberFormat nf   =   NumberFormat.getPercentInstance();     注释掉的也是一种方法
            //nf.setMinimumFractionDigits( 2 );        保留到小数点后几位
            DecimalFormat df1 = new DecimalFormat("0.00%");    //##.00%   百分比格式，后面不足2位的用0补齐
            //result=nf.format(tempresult);

            return df1.format(tempresult).toString();

        }else {
            return "0.00%";
        }

    }
    /**
     *返回String 日期转字符串  自行传入类型 typr:
     */
    public static String toStr(Date date, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat(type);
        if (null!=date) {
            return sdf.format(date);
        }
        return "";
    }

    public static String toStr(Double date) {
        if (null!=date) {
            return date.toString();
        }
        return "";
    }

    /**返回date 自行传入格式化类型**/
    public static Date toDate(String dateStr, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat(type);
        if (null!=dateStr &&!"".equals(dateStr.trim())) {
            try {
                return sdf.parse(dateStr);
            } catch (ParseException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    public static String getFormatMonth(String strNumber){
        if(isNull(strNumber)){
            return "1";
        }
        int number = 1;
        try {
            number = Integer.parseInt(strNumber);
        } catch (Exception e) {
            return "1";
        }
        return number+"";
    }

    public static boolean isExitInArray(String str,String[] strArray){
        boolean result = false;
        for(int i=0,j=strArray.length;i<j;i++){
            if(strArray[i].equals(str)){
                result = true;
                break;
            }
        }
        return result;
    }

    public static String getBestEPResult(String str){
        if(str.contains("A+")) {
            return "A+";
        } else if(str.contains("A")) {
            return "A";
        } else if(str.contains("B")) {
            return "B";
        } else if(str.contains("C")) {
            return "C";
        } else if(str.contains("D")) {
            return "D";
        } else if(str.contains("E")) {
            return "E";
        }
        return "";
    }

    /**
     * Object转String
     * author: WangHui
     * @since 2016/7/7
     */
    public static String objToStr(Object obj) {
        return isNull(obj) ? "" : obj.toString();
    }

    /**
     * 将OBJ转换为double
     * 开发者：WangHui
     * @since 2016/7/7
     */
    public static double objToDouble(Object obj) {
        return isNull(obj) ? 0 : Double.valueOf(obj.toString());
    }

    /**
     * 设置Double默认为0
     * 开发者：WangHui
     * @since 2016/7/7
     */
    public static double defaultDouble(Float f) {
        return f == null ? 0D : f;
    }

    /**
     * 占比  total 总值  f占比值  scale小数位 为空取默认值
     * 开发者：WangHui
     * @since 2016/7/7
     */
    public static double getRatioByScale(Double total, Double f, Integer scale) {
        if(total == null || total == 0 || f == null || f == 0) {
            return 0F;
        } else {
            if(scale == null) {
                scale = DEFAULT_SCALE;
            }
            double ratio = (f/total)*100;  //四舍五入模式
            return BigDecimal.valueOf(ratio).setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
    }

    /**
     * 提供精确的小数位四舍五入处理
     * Author: WangHui
     * @since 2016/7/13
     */
    public static String rounds(Double d, Integer scale){
        if(d == null || d == 0) {
            return  "0.00";
        }
        if(scale == null || scale < 0) {
            scale = DEFAULT_SCALE;
        }
        BigDecimal mData = new BigDecimal(d);
        return mData.setScale(scale, BigDecimal.ROUND_HALF_UP).toString();
    }



    /**
     * 取得n的区间索引
     * @param n
     * @param ns
     * @return
     */
    public static int getIndex(int n, Integer[] ns) {
        int index = 0;
        if(ns != null && ns.length > 0) {
            for (int i=0; i<ns.length; i++) {
                if(i==0) {
                    if(n<ns[i]) {
                        index = i;
                        break;
                    }
                } else if (i==ns.length-1) {
                    if(n>=ns[i-1] && n<ns[i]) {
                        index = i;
                        break;
                    }
                    if( n>=ns[i]) {
                        index = ns.length;
                        break;
                    }
                } else {
                    if(n>=ns[i-1] && n<ns[i]) {
                        index = i;
                        break;
                    }
                }
            }
        }
        return index;
    }

    /**
     * 根据索引拼名称
     * @param i
     * @param ns
     * @return
     */
    public static String getName(int i, Integer[] ns) {
        String name = "";
        if(i == 0) {
            name = "<" + ns[0];
        } else if (i == ns.length) {
            name = ">=" + ns[ns.length-1];
        } else {
            name = ns[i-1] + "-" + (ns[i]-1);
        }
        return name;
    }

    /**
     * 去掉空值
     * @param strs
     * @return
     */
    public static String[] cleanString(String[] strs) {
        String str = "";
        if(strs != null && strs.length > 0) {
            for(String s : strs) {
                if(!StringUtils.isNull(s)) {
                    str = str + s + ",";
                }
            }
            str = str.substring(0, str.length()-1);
            strs = str.split(",");
        }
        return strs;
    }

    /**
     * Object转String
     * @param obj
     * @return
     */
    public static String toString(Object obj) {
        return obj == null ? null : obj.toString();
    }

    /**
     * Object转Integer
     * @param obj
     * @return
     */
    public static Integer toInteger(Object obj) {
        return isNull(obj) ? null : Integer.valueOf(obj.toString());
    }
    /**
     * 清除字符串换行符，前后空格
     * @param obj
     * @return
     */
    public static String toClean(String obj) {
        obj=obj.replaceAll("\r|\n", "").replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "").trim();
        return obj;
    }
    /**
     * 转大写
     * @param str
     * @return
     */
    public static String strToUpperCase(String str) {
        return str == null ? null : str.toUpperCase();
    }

    //阿拉伯数字转化为中文数字(1到10）
    public static char numberToCHSnum(int index){
        String string = "一二三四五六七八九十";
        return string.charAt(index - 1);
    }

    /**
     * 生成图片文件名
     * @return
     */
    public static String getPhotoFileName() {
//        return getRandomString(Constants.PHOTO_LEN) + Constant.UNDERLINE + getDateString();
        return getStringRandom(Constant.PHOTO_LEN) + Constant.UNDERLINE + getDateString();
    }
    //生成随机数字和字母,
    public static String getStringRandom(int length) {

        String val = "";
        Random random = new Random();
        for(int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }
    /**
     * 当前时间
     * @return
     */
    public static String getDateString() {
        return String.valueOf(System.currentTimeMillis());
    }


    /**
     * 将对象里的字符串字段赋默认值为空字符串，数字字段默认值为0
     * 为了兼容PeopleSoft的数据库要求
     * @param obj   对象实例
     */
    public static void parseNull2Space(Object obj){
        try {
            Field[] fields = obj.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                Field f = fields[i];
                f.setAccessible(true);
                Object valObj = f.get(obj);
                if(valObj == null || valObj.toString().length() == 0) {
                    String name = f.getName();
//                    System.out.println(name);
                    String setMethodName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
                    Method setMethod = obj.getClass().getDeclaredMethod(setMethodName, f.getType());
                    setMethod.setAccessible(true);
//                    System.out.println(name + " = " + f.getType().getName());
                    if("java.lang.String".equals(f.getType().getName())) {
                        // 字符串默认为空格
                        setMethod.invoke(obj, Constant.STRING_SPACE);
                    } else if("java.lang.Integer".equals(f.getType().getName())) {
                        // 数字默认为0
                        setMethod.invoke(obj, 0);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
 　　* 将原数据前补零，补后的总长度为指定的长度，以字符串的形式返回
 　　* @param sourceDate 原始数字
 　　* @param formatLength 字符总长度为
 　　* @return 重组后的数据
 　　*/
    public static String frontCompWithZero(int sourceDate, int formatLength) {
        //0 指前面补充零 d 代表为正数
        String newString = String.format("%0" + formatLength + "d", sourceDate);
        return newString;
    }

}
